import { UploadFile } from '@/models/UploadFile.js';
import { ref, reactive, computed, onUnmounted } from 'vue';
import { UploadFile } from '../models/UploadFile.js';

export function useFileUpload(options = {}) {
  const {
    maxFileSize = 2 * 1024 * 1024 * 1024, // 2GB
    allowedTypes = [],
    maxConcurrentUploads = 3,
    chunkSize = 512 * 1024, // 512KB
    autoUpload = false,
    uploadEndpoint = '/api/upload'
  } = options;

  // 状态
  const files = reactive([]);
  const isUploading = ref(false);
  const totalProgress = ref(0);
  const dragOver = ref(false);

  // 计算属性
  const stats = computed(() => {
    const total = files.length;
    const completed = files.filter(f => f.status === 'completed').length;
    const uploading = files.filter(f => f.status === 'uploading').length;
    const pending = files.filter(f => f.status === 'pending').length;
    const error = files.filter(f => f.status === 'error').length;
    const cancelled = files.filter(f => f.status === 'cancelled').length;

    return { total, completed, uploading, pending, error, cancelled };
  });

  const hasPendingFiles = computed(() =>
    files.some(file => file.status === 'pending')
  );

  const totalUploadSpeed = computed(() =>
    files.reduce((sum, file) => sum + file.uploadSpeed, 0)
  );

  // 文件验证
  const validateFile = (file) => {
    const errors = [];

    // 文件大小验证
    if (file.size > maxFileSize) {
      errors.push(`文件大小不能超过 ${formatFileSize(maxFileSize)}`);
    }

    // 文件类型验证
    if (allowedTypes.length > 0 && !allowedTypes.some(type =>
      file.type.startsWith(type) || file.name.toLowerCase().endsWith(type)
    )) {
      errors.push(`不支持的文件类型，支持的类型: ${allowedTypes.join(', ')}`);
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  };

  // 添加文件
  const addFiles = (fileList, fileType = 'file') => {
    const addedFiles = [];

    for (let file of fileList) {
      const validation = validateFile(file);

      if (validation.isValid) {
        const uploadFile = new UploadFile(file, null, fileType);
        files.push(uploadFile);
        addedFiles.push(uploadFile);

        // 触发添加文件事件
        emit('fileAdded', uploadFile);

        // 如果启用自动上传，立即开始上传
        if (autoUpload) {
          uploadFile(uploadFile.id);
        }
      } else {
        // 触发验证错误事件
        emit('validationError', { file, errors: validation.errors });
      }
    }

    updateTotalProgress();
    return addedFiles;
  };

  // 移除文件
  const removeFile = (fileId) => {
    const index = files.findIndex(f => f.id === fileId);
    if (index !== -1) {
      const [removedFile] = files.splice(index, 1);

      // 清理预览URL
      if (removedFile.previewUrl) {
        URL.revokeObjectURL(removedFile.previewUrl);
      }

      emit('fileRemoved', removedFile);
      updateTotalProgress();
    }
  };

  // 清空所有文件
  const clearAll = () => {
    // 清理所有预览URL
    files.forEach(file => {
      if (file.previewUrl) {
        URL.revokeObjectURL(file.previewUrl);
      }
    });

    files.splice(0, files.length);
    totalProgress.value = 0;
    emit('allCleared');
  };

  // 上传单个文件
  const uploadFile = async (fileId) => {
    const file = files.find(f => f.id === fileId);
    if (!file || file.status === 'uploading' || file.status === 'completed') {
      return;
    }

    file.setStatus('uploading');
    emit('uploadStarted', file);

    try {
      // 模拟上传过程 - 在实际项目中替换为真实的上传逻辑
      await simulateUpload(file);

      file.setStatus('completed');
      emit('uploadCompleted', file);
      updateTotalProgress();

    } catch (error) {
      file.setStatus('error', error.message);
      emit('uploadError', { file, error });
    }
  };

  // 模拟上传（实际项目中替换为真实的上传逻辑）
  const simulateUpload = (file) => {
    return new Promise((resolve, reject) => {
      const totalChunks = Math.ceil(file.file.size / chunkSize);
      let uploadedChunks = 0;
      const startTime = Date.now();

      const uploadChunk = () => {
        setTimeout(() => {
          if (file.status === 'cancelled') {
            reject(new Error('Upload cancelled'));
            return;
          }

          uploadedChunks++;
          const progress = (uploadedChunks / totalChunks) * 100;

          // 计算上传速度
          const currentTime = Date.now();
          const elapsedTime = (currentTime - startTime) / 1000;
          const uploadSpeed = (file.file.size * (progress / 100)) / (elapsedTime || 1);

          file.updateProgress(progress, uploadSpeed);
          emit('uploadProgress', file);

          if (uploadedChunks < totalChunks) {
            uploadChunk();
          } else {
            resolve();
          }
        }, 200); // 模拟网络延迟
      };

      uploadChunk();
    });
  };

  // 取消上传
  const cancelUpload = (fileId) => {
    const file = files.find(f => f.id === fileId);
    if (file && file.status === 'uploading') {
      file.cancel();
      emit('uploadCancelled', file);
    }
  };

  // 重试上传
  const retryUpload = (fileId) => {
    const file = files.find(f => f.id === fileId);
    if (file && (file.status === 'error' || file.status === 'cancelled')) {
      file.setStatus('pending');
      file.updateProgress(0);
      uploadFile(fileId);
    }
  };

  // 上传所有文件
  const uploadAll = async () => {
    if (isUploading.value) return;

    isUploading.value = true;
    emit('uploadAllStarted');

    const pendingFiles = files.filter(f => f.status === 'pending');

    // 控制并发上传数量
    const chunks = [];
    for (let i = 0; i < pendingFiles.length; i += maxConcurrentUploads) {
      chunks.push(pendingFiles.slice(i, i + maxConcurrentUploads));
    }

    for (const chunk of chunks) {
      await Promise.all(chunk.map(file => uploadFile(file.id)));
    }

    isUploading.value = false;
    emit('uploadAllCompleted');
  };

  // 更新总进度
  const updateTotalProgress = () => {
    if (files.length === 0) {
      totalProgress.value = 0;
      return;
    }

    const total = files.reduce((sum, file) => sum + file.progress, 0);
    totalProgress.value = total / files.length;
  };

  // 事件系统
  const eventHandlers = {};

  const on = (event, handler) => {
    if (!eventHandlers[event]) {
      eventHandlers[event] = [];
    }
    eventHandlers[event].push(handler);
  };

  const off = (event, handler) => {
    if (eventHandlers[event]) {
      eventHandlers[event] = eventHandlers[event].filter(h => h !== handler);
    }
  };

  const emit = (event, data) => {
    if (eventHandlers[event]) {
      eventHandlers[event].forEach(handler => handler(data));
    }
  };

  // 拖放功能
  const handleDragOver = (event) => {
    event.preventDefault();
    dragOver.value = true;
  };

  const handleDragLeave = (event) => {
    event.preventDefault();
    dragOver.value = false;
  };

  const handleDrop = (event) => {
    event.preventDefault();
    dragOver.value = false;

    const droppedFiles = event.dataTransfer.files;
    if (droppedFiles.length > 0) {
      addFiles(droppedFiles);
    }
  };

  // 清理函数
  const cleanup = () => {
    files.forEach(file => {
      if (file.previewUrl) {
        URL.revokeObjectURL(file.previewUrl);
      }
    });
  };

  // 组件卸载时清理
  onUnmounted(() => {
    cleanup();
  });

  return {
    // 状态
    files: reactive(files),
    isUploading,
    totalProgress,
    dragOver,

    // 计算属性
    stats,
    hasPendingFiles,
    totalUploadSpeed,

    // 方法
    addFiles,
    removeFile,
    clearAll,
    uploadFile,
    cancelUpload,
    retryUpload,
    uploadAll,

    // 拖放方法
    handleDragOver,
    handleDragLeave,
    handleDrop,

    // 事件系统
    on,
    off,

    // 工具函数
    validateFile,
    formatFileSize: (bytes) => formatFileSize(bytes)
  };
}

// 工具函数
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}